package com.zzzzzz.core.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.zzzzzz.common.exception.NoSuchClassNameException;
import com.zzzzzz.core.exception.SystemException;
import com.zzzzzz.core.model.po.ClassName;

@Repository
public class ClassNameDao extends BaseDao {
	
	private static final String ADD = "insert into class_name(class_name_id, value_) values(:classNameId, :value)";
	
	private static final String FIND_BY_ID = "select * from class_name where class_name_id = ?";
	
	private static final String FIND_BY_VALUE = "select * from class_name where value_ = ?";

	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No ClassName exists with the primary key ";
	
	private static final String _NO_SUCH_ENTITY_WITH_KEY = "No ClassName exists with the key {";
	
	protected class ClassNameRowMapper implements RowMapper<ClassName> {
//		@Override
		public ClassName mapRow(ResultSet rs, int rn) throws SQLException {
			ClassName className = new ClassName();
			className.setClassNameId(rs.getLong("class_name_id"));
			className.setValue(rs.getString("value_"));
			return className;
		}
	}
	
	public void add(ClassName className) throws SystemException {
		try{
			long classNameId = updateForLongKey(ADD, className);
			className.setClassNameId(classNameId);
		}catch (Exception e) {
			throw processException(e);
		}
	}
	
	public ClassName findById(long classNameId) throws NoSuchClassNameException, SystemException {
		ClassName className = null;
		try{
			className = findOne(FIND_BY_ID, new ClassNameRowMapper(), classNameId);
		}catch(Exception e) {
			throw processException(e);
		}
		if(className == null) {
			throw new NoSuchClassNameException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + classNameId);
		}
		return className;
	}
	
	public ClassName findByValue(String value) throws SystemException {
		ClassName className = null;
		try{
			className = findOne(FIND_BY_VALUE, new ClassNameRowMapper(), value);
		}catch(Exception e) {
			throw processException(e);
		}
		return className;
	}

}